import axios from "axios";

import {HttpCode} from './httpcode'
import { message as Message } from "antd";

const baseUrl = "/api";
class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  getInsideConfig() {
    const config = {
      baseUrl: this.baseUrl,
      header: {},
    };
    return config;
  }
  interceptors(instance) {
    // 添加请求拦截器
    instance.interceptors.request.use(
      function (config) {
        // 在发送请求之前做些什么
        config.headers.Accept = "application/json";
        config.headers.Authorization = `Bearer ${localStorage.getItem(
          "token"
        )}`;
        return config;
      },
      function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    instance.interceptors.response.use(
      function (response) {
        // 对响应数据做点什么
        return response;
      },
      function (error) {
        const {
          response: { status, data },
        } = error;
        const message = error.response.data.message;
        switch (status) {
          case HttpCode.UNAUTHORIZED:
            break;
          case HttpCode.UNPROCESSABLE_ENTITY:
            break;
          case HttpCode.FORBIDDEN:
            Message.error(message ?? "没有操作权限");
            break;
          case HttpCode.NOT_FOUND:
            Message.error("请求资源不存在");
            break;
          case HttpCode.INTERNAL_SERVER_ERROR:
            if (error.response.data.message) {
              Message.error(error.response.data.message);
            }
            if (error.response.data.error) {
              Message.error(error.response.data.error);
            }
            if (error.response.data.errors) {
              Message.error(error.response.data.errors);
            }
            break;
          case HttpCode.TOO_MANY_REQUESTS:
            Message("请求过于频繁，请稍候再试");
            break;
          default:
            if (message) {
              Message(message ?? "服务器错误");
            }
        }
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    const instance = axios.create();
    options = { ...this.getInsideConfig(), ...options };
    this.interceptors(instance);
    return instance(options);
  }
}
export default new HttpRequest(baseUrl);
